<?php
/**
 * Created by PhpStorm.
 * User: xudongsheng
 * Date: 2017/9/10
 * Time: 下午6:32
 */

namespace app\admin\model;
use Category\Category;
use think\Model;

class column extends Model
{
    /**
     * 单页模型
     */
    const SINGLE_PAGE   =  0;
    // 外链
    const LINKS_TYPE    =  1;
    // 单例模式
    protected static $instance   =   null;

    /** 获取器 处理 状态
     * @param $value
     * @param $data
     * @return string
     */
    public function getStatusTextAttr($value,$data){
        return $data['status']?'正常':'禁止';
    }

    /** 获取器 处理 特殊模型
     * @param $value
     * @param $data
     * @return string
     */
    public function getModelNameAttr($value,$data){
        return $data['type']?'外部链接':($data['model_id']?$this['model']['name']:'单页模型');
    }

    /** model
     * @return $this
     */
    public function model(){
        return $this->hasOne('model','model_id','model_id')->field(['model_id','name','tablename']);
    }

    /** 获取 内容 菜单
     * @return array
     */
    public  function getContentMenu(){
        $data  = self::with('model')
                    ->where('type','<>',1)
                    ->where('pid',0)
                    ->order('sort','desc')
                    ->field('name,column_id,model_id,pid')
                    ->select();
        return self::formatResult($data);
    }

    //Content manage

    /** 更新 菜单
     * @return bool
     */
    public static function updateNavMenu(){
        $data  = self::with('model')
                    ->where('type','<>',1)
                    ->where('pid',0)
                    ->order('sort','desc')
                    ->field('name,column_id,model_id,pid')
                    ->select();
        $columnNav  =   AdminNav::get(['name'=>'#columnNav']);
        if (empty($columnNav)){
            $columnNav =  AdminNav::create(['name'=>'#columnNav','title'=>'内容管理','ico'=>'fa fa-columns']);
        }
        AdminNav::destroy(['pid'=>$columnNav->admin_nav_id]);
        if (empty($data)){ return true; }
        foreach ($data as $v){
            $tmp['title']   =   $v['name'];
            // 求出 tablename
            $tablename      =   $v['model_id'] != self::SINGLE_PAGE ? $v['model']['tablename']:'single_page';
            $tmp['name']    =   (isset($v['type']) AND $v['type'] == self::LINKS_TYPE)?'column/editColumn':$tablename.'/lists';
            $tmp['params']  =   'column_id='.$v['column_id'];
            $tmp['pid']     =   $columnNav->admin_nav_id;
            $tmp['ico']     =   '';
            AdminNav::create($tmp,true);
        }
        // 缓存
        return true;
    }

    /** 导航 链接 格式化数据
     * @param $data
     * @return array
     */
    public  function formatResult($data){
        $tmp = [];
        foreach ($data as $k=>$v){ //Single page
            $tmp[$k]['name']        = $v['name'];
            $tmp[$k]['column_id']   = $v['column_id'];
            $tmp[$k]['model_id']    = $v['model_id'];
            $tmp[$k]['tablename']   = $v['model_id'] != self::SINGLE_PAGE ? $v['model']['tablename']:'single_page';
            $tmp[$k]['pid']         = $v['pid'];
            $tmp[$k]['url']         = (isset($v['type']) AND $v['type'] == self::LINKS_TYPE)
                                    ?url('column/editColumn',['column_id'=>$tmp[$k]['column_id']])
                                    :url($tmp[$k]['tablename'].'/lists',['column_id'=>$tmp[$k]['column_id']],
            $tmp[$k]['data']    =   $v
            );
        }
        return $tmp;
    }

    public function columnAllData(){

    }

    /** 求面包屑
     * @param $column_id
     * @return array
     */
    public  function crumbs($column_id){
        //求出 所有的 父级 分类
        $parents = Category::getParents(
                $this->columnNotLinksAllData(),
                $column_id,'column_id'
            );
        return $parents;
    }

    protected $NotLinksAllData;

    /** 获取 除外链 之外的 所有数据
     * @return array
     */
    protected function columnNotLinksAllData(){
        if ($this->NotLinksAllData) return $this->NotLinksAllData;
        $data  = self::with('model')
            ->where('type','<>',1)  // 不能是外链
            ->field('name,column_id,model_id,pid,alias,catpic,is_show')
            ->select();
        return self::formatResult($data);
    }

    /** 获取当前分类的 一级子分类
     * @param $column_id
     * @return array
     */
    public function classAChild($column_id){
      return  Category::getChild($this->columnNotLinksAllData(),$column_id);
    }

    /** 获取当前栏目 所有子栏目 id
     * @param $column_id
     * @return array
     */
    public function getChildsId($column_id){
        return Category::getChildsId(
            $this->columnNotLinksAllData(),$column_id,true,'column_id'
        );
    }

    /** 获取 子 栏目
     * @param $column_id
     * @param bool $flag
     * @return array
     */
    public function getchilds($column_id,$flag = true){
        $columnAll  =   $this->columnNotLinksAllData();
        $data = Category::toLevel($columnAll,$column_id,'column_id');
        if ($flag){
            foreach ($columnAll as $v){
                if ($v['column_id'] == $column_id){
                    array_unshift($data,$v);
                    break;
                }
            }
        }
        foreach ($data as &$v){
            $v['delimiter']  =   isset($v['level'])?str_repeat('———',$v['level']):'';
        }
        return $data;
    }

    public function modelNameByColumn(){
        $modelName      =   strtolower(request()->controller());
        $nowModelName   =   Category::getLevelOfModel($this->columnNotLinksAllData(),$modelName);
        return Category::toLevel($nowModelName,0,'column_id');
    }

    /** 约定 每个 模型 都要 有  title  click thumbnail description release_time sort status column_id 等基础字段
     * @param column $column
     */
    public function showColumnsLevel(self $column){
        $columnAll  =   $this->columnNotLinksAllData();
        $lists      =   $this->formatResult([$column]);
        $childs     =   Category::getChilds($columnAll,$column->column_id,'column_id');
        $lists      =   array_merge($lists,$childs);
        $content    =   [];
        foreach ($lists as $key   =>  $v){
                if ($v['model_id'] != self::SINGLE_PAGE){
                    $class = '\app\admin\model\\'.ucwords($v['tablename']);
                    $current = $class::with('column_model')
                            ->where(['column_id' => $v['column_id'],'status'  =>    1])
                            ->field($v['tablename'].'_id,'.'click,column_id,click,title,thumbnail,description,release_time')
                            ->order('sort','desc')
                            ->select();
                    if(empty($current)) continue;
                    $content    =   array_merge($content,$current);
                }

        }
        return $content;
    }

    public function showColumnOfContent($childColumn){
        // 2 种情况 一种 单页 一种  普通模型 方式
        $tmp    =   [];
       foreach ($childColumn as $k=>$v){
           if ($v['model_id']   ==  self::SINGLE_PAGE){
                $tmp[$k]['title']       =    $v['name'];
                $tmp[$k]['alias']       =    $v['data']->alias;
                $tmp[$k]['catpic']      =    $v['data']->catpic;
                $tmp[$k]['content']     =    htmlspecialchars_decode($v['data']->content);
                continue;
           }
           $class = '\app\admin\model\\'.ucwords($v['tablename']);
           $current = $class::with('column_model')
               ->where(['column_id' => $v['column_id'],'status'  =>    1])
               ->field($v['tablename'].'_id,'.'click,column_id,click,title,thumbnail,description,release_time')
               ->order('sort','desc')
               ->select();
           if(empty($current)) continue;
           $tmp[$k] = $current;
       }
       return $tmp;
    }



    /** 单例模式 统一入口
     * @return column|null
     */
    public static function init(){
        if (is_null(self::$instance)){
            self::$instance =   new self();
        }
        return self::$instance;
    }


}